#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库初始化脚本
用于将JSON数据文件导入到对应的数据库表中
"""

import json
import os
from typing import Dict, Any
import asyncio
import typer
from tortoise import Tortoise

from applications.config import settings
from applications.models import Dept, Power, Role, User

app = typer.Typer(help="Pear Admin 数据库初始化工具")


async def init_db():
    """初始化数据库连接"""
    await Tortoise.init(
        # config=settings.TORTOISE_ORM,
        db_url=settings.DATABASE_URI,
        modules={"models": ["applications.models"]},
        _create_db=True,
    )
    await Tortoise.generate_schemas()


async def close_db():
    """关闭数据库连接"""
    await Tortoise.close_connections()


def load_json_data(filename: str) -> list:
    """从data目录加载JSON数据"""
    file_path = os.path.join("data", filename)
    with open(file_path, "r", encoding="utf-8") as f:
        return json.load(f)


async def import_dept_data():
    """导入部门数据"""
    typer.echo("正在导入部门数据...")
    depts_data = load_json_data("admin_dept.json")

    for dept_data in depts_data:
        # 移除时间字段，让数据库自动生成
        dept_dict = {
            "id": dept_data["id"],
            "parent_id": dept_data["parent_id"],
            "dept_name": dept_data["dept_name"],
            "sort": dept_data["sort"],
            "leader": dept_data["leader"],
            "phone": dept_data["phone"],
            "email": dept_data["email"],
            "status": dept_data["status"],
            "remark": dept_data["remark"],
            "address": dept_data["address"],
        }
        await Dept.create(**dept_dict)

    typer.echo(f"成功导入 {len(depts_data)} 条部门数据")


async def import_role_data():
    """导入角色数据"""
    typer.echo("正在导入角色数据...")
    roles_data = load_json_data("admin_role.json")

    for role_data in roles_data:
        role_dict = {
            "id": role_data["id"],
            "name": role_data["name"],
            "code": role_data["code"],
            "enable": role_data["enable"],
            "remark": role_data["remark"],
            "details": role_data["details"],
            "sort": role_data["sort"],
        }
        await Role.create(**role_dict)

    typer.echo(f"成功导入 {len(roles_data)} 条角色数据")


async def import_power_data():
    """导入权限数据"""
    typer.echo("正在导入权限数据...")
    powers_data = load_json_data("admin_power.json")

    for power_data in powers_data:
        power_dict = {
            "id": power_data["id"],
            "name": power_data["name"],
            "type": power_data["type"],
            "code": power_data["code"],
            "url": power_data["url"],
            "open_type": power_data["open_type"],
            "parent_id": power_data["parent_id"],
            "icon": power_data["icon"],
            "sort": power_data["sort"],
            "enable": power_data["enable"],
        }
        await Power.create(**power_dict)

    typer.echo(f"成功导入 {len(powers_data)} 条权限数据")


async def import_user_data():
    """导入用户数据"""
    typer.echo("正在导入用户数据...")
    users_data = load_json_data("admin_user.json")

    for user_data in users_data:
        user_dict = {
            "id": user_data["id"],
            "username": user_data["username"],
            "realname": user_data["realname"],
            "avatar": user_data["avatar"],
            "remark": user_data["remark"],
            "password_hash": user_data["password_hash"],
            "enable": user_data["enable"],
            "dept_id": user_data["dept_id"],
        }
        await User.create(**user_dict)

    typer.echo(f"成功导入 {len(users_data)} 条用户数据")


async def clear_tables():
    """清空所有相关表数据"""
    typer.echo("正在清空所有相关表数据...")
    await User.all().delete()
    await Role.all().delete()
    await Power.all().delete()
    await Dept.all().delete()
    typer.echo("所有相关表数据已清空")


@app.command()
def init(clear: bool = typer.Option(False, "--clear", "-c", help="是否先清空数据")):
    """初始化数据库，导入所有JSON数据"""

    async def _init():
        await init_db()

        if clear:
            await clear_tables()

        try:
            await import_dept_data()
            await import_role_data()
            await import_power_data()
            await import_user_data()
            typer.echo("数据库初始化完成！")
        except Exception as e:
            typer.echo(f"导入数据时出错: {e}")
        finally:
            await close_db()

    asyncio.run(_init())


@app.command()
def reset():
    """重置数据库（先清空再导入）"""

    async def _reset():
        await init_db()
        await clear_tables()

        try:
            await import_dept_data()
            await import_role_data()
            await import_power_data()
            await import_user_data()
            typer.echo("数据库重置完成！")
        except Exception as e:
            typer.echo(f"重置数据时出错: {e}")
        finally:
            await close_db()

    asyncio.run(_reset())


if __name__ == "__main__":
    app()
